import { _decorator, Component, EventTouch, Input, input, Node, math, Collider, ITriggerEvent, AudioSource, Prefab } from 'cc';
import { Constant } from '../framework/Constant';
const { ccclass, property } = _decorator;

@ccclass('SelfPlane')
export class SelfPlane extends Component {

    public lifeValue = 5;

    private _currentLife = 0;
    public isDie = false;
    @property
    private speed = 1;

    @property(Node)
    private explore: Node = null;

    @property(Node)
    private bloodFace: Node = null;

    @property(Node)
    private blood: Node = null;

    private moveMultiple = 0.04;

    private delta = new math.Vec2();

    private audioSource: AudioSource = null;

    protected onEnable(): void {
        const collider = this.getComponent(Collider);
        collider.on('onTriggerEnter', this.triggerEnter, this);
    }
    protected onDestroy(): void {
        const collider = this.getComponent(Collider);
        collider.off('onTriggerEnter', this.triggerEnter, this);
    }

    start() {
        input.on(Input.EventType.TOUCH_MOVE, this.touchMove, this);

        this.init();
        this.audioSource = this.getComponent(AudioSource);
    }

    public init() {
        this._currentLife = this.lifeValue;
        this.isDie = false;
        this.node.active = true;
        this.explore.active = false;
        this.bloodFace.setScale(1, 1, 1); 
    }

    touchMove(event: EventTouch) {
        event.getDelta(this.delta);

        let pos = this.node.position;
        this.node.setPosition(pos.x + this.moveMultiple * this.speed * this.delta.x, pos.y, pos.z - this.moveMultiple * this.speed * this.delta.y)
    }

    triggerEnter(event: ITriggerEvent) {
        const otherCollider = event.otherCollider.getGroup();
        if (otherCollider === Constant.ColliderType.ENEMY_BULLET || otherCollider === Constant.ColliderType.ENEMY_PLANE) {
            console.log('reduce blood');
            if (this._currentLife ===this.lifeValue) {
                this.blood.active = true;
            }
            this._currentLife--;
            this.bloodFace.setScale(this._currentLife / this.lifeValue, 1, 1);
            if (this._currentLife <= 0) {
                this.audioSource.play();
                this.explore.active = true;
                this.isDie = true;
                this.blood.active=false;
            }
        }
    }

    update(deltaTime: number) {

    }
}

